<template>
  <div class="forum-page">
    <div class="content-wrapper">
      <div class="page-header">
        <h1>论坛讨论</h1>
        <el-button type="primary" @click="handleCreate" v-if="userStore.isLoggedIn">
          发布帖子
        </el-button>
      </div>

      <!-- 帖子列表 -->
      <div class="post-list" v-loading="loading">
        <el-card v-for="post in posts" :key="post.id" class="post-card">
          <div class="post-header">
            <div class="author-info">
              <el-avatar :src="post.avatar" :size="40">{{ post.username?.charAt(0) }}</el-avatar>
              <div class="author-meta">
                <span class="username">{{ post.username }}</span>
                <span class="time">{{ formatDate(post.createTime) }}</span>
              </div>
            </div>
            <div class="post-actions" v-if="post.isAuthor || userStore.isAdmin">
              <el-button type="danger" link @click="handleDelete(post)">删除</el-button>
            </div>
          </div>

          <div class="post-content" @click="handlePostClick(post)">
            <h2 class="title">{{ post.title }}</h2>
            <p class="content">{{ post.content }}</p>
          </div>

          <div class="post-footer">
            <div class="stats">
              <span class="views">
                <el-icon><View /></el-icon>
                {{ post.viewCount }}
              </span>
              <span class="comments">
                <el-icon><ChatLineRound /></el-icon>
                {{ post.commentCount }}
              </span>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { View, ChatLineRound } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const posts = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString()
}

const loadPosts = async () => {
  loading.value = true
  try {
    const res = await request.get('/api/forum/posts', {
      params: {
        page: currentPage.value,
        size: pageSize.value
      }
    })
    if (res.code === 200) {
      posts.value = res.data.records
      total.value = res.data.total
    }
  } catch (error) {
    console.error('加载帖子列表失败:', error)
    ElMessage.error('加载帖子列表失败')
  } finally {
    loading.value = false
  }
}

const handleCreate = () => {
  router.push('/front/forum/create')
}

const handlePostClick = (post) => {
  router.push(`/front/forum/post/${post.id}`)
}

const handleDelete = async (post) => {
  try {
    await ElMessageBox.confirm('确定要删除这个帖子吗？', '提示', {
      type: 'warning'
    })
    const res = await request.delete(`/api/forum/posts/${post.id}`)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadPosts()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除帖子失败:', error)
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadPosts()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadPosts()
}

onMounted(() => {
  loadPosts()
})
</script>

<style lang="scss" scoped>
.forum-page {
  .content-wrapper {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;

    h1 {
      margin: 0;
      font-size: 28px;
      color: #303133;
    }
  }

  .post-card {
    margin-bottom: 20px;

    .post-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      .author-info {
        display: flex;
        align-items: center;
        gap: 12px;

        .author-meta {
          display: flex;
          flex-direction: column;

          .username {
            font-weight: bold;
            color: #303133;
          }

          .time {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }

    .post-content {
      cursor: pointer;

      .title {
        margin: 0 0 10px;
        font-size: 18px;
        color: #303133;
      }

      .content {
        color: #606266;
        line-height: 1.6;
        margin: 0;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
      }
    }

    .post-footer {
      margin-top: 15px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .stats {
        display: flex;
        gap: 20px;
        color: #909399;
        font-size: 14px;

        span {
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }
    }
  }

  .pagination-container {
    margin-top: 30px;
    display: flex;
    justify-content: center;
  }
}
</style> 